package com.yunhe.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yunhe.javabean.Product;
import com.yunhe.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/product")
public class ProductController {
    @Autowired
    ProductService productService;

    @RequestMapping("/findAll")
    public String findAll(HttpServletRequest request, @RequestParam(value = "page",required = false,defaultValue = "1") int page, @RequestParam(value = "limit",required = false,defaultValue = "5")int limit,@RequestParam(value = "productName",required = false,defaultValue = "")String productName){
        PageHelper.startPage(page, limit);
        List<Product> all = productService.findAll(productName);
        PageInfo<Product> pageInfo=new PageInfo<Product>(all);
        request.setAttribute("pageInfo",pageInfo);
        System.out.println(pageInfo);
        request.setAttribute("value",productName);

        return "/product/product-list";
    }





    //修改产品
    //首先需要根据ia查询产品信息 在修改页面显示
    @RequestMapping("/findById")
    public String findById(HttpServletRequest request,int id){
        Product product = productService.findById(id);
        request.setAttribute("product",product);
        return "/product/product-edit";
    }

    //修改页面点击修改按钮将数据提交进行修改
    @RequestMapping("/edit")
    public String edit(Product product){
        int i = productService.editById(product);
        return "redirect:/product/findAll";
    }


    //产品详情
    //首先需要根据ia查询产品信息 在修改页面显示
    @RequestMapping("/show")
    public String show(HttpServletRequest request,int id){
        Product product = productService.findById(id);
        request.setAttribute("product",product);
        return "/product/product-show";
    }


    //产品添加
    //首先需要根据ia查询产品信息 在修改页面显示
    @RequestMapping("/add")
    public String show(Product product){
        productService.add(product);
        return "redirect:/product/findAll";
    }
    //产品删除
    //首先需要根据ia查询产品信息 在修改页面显示
    @RequestMapping("/deleteById")
    public String delete(int id){
        productService.delete(id);
        return "redirect:/product/findAll";
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @RequestMapping("/deleteIds")
    @ResponseBody
    public String deleteIds(@RequestBody List<Integer> ids){
        //删除操作
        productService.deleteIds(ids);
        return "/product/findAll";
    }
}
